package com.sam.library.document;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;

/**
 * @author wanghao
 * @date 2022/11/1.
 * @des
 */
public class FileAdapter extends RecyclerView.Adapter<FileAdapter.ViewHolder> implements View.OnClickListener {

    private File[] mFiles;
    private LayoutInflater mLayoutInflater;
    private OnDirectoryClickListener listener;

    public FileAdapter(OnDirectoryClickListener listener) {
        this.listener = listener;
    }

    public void setData(File[] files) {
        mFiles = files;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        initInflater(parent);
        View view = mLayoutInflater.inflate(R.layout._sam_document_item, parent, false);
        view.setOnClickListener(this);
        return new ViewHolder(view);
    }

    private void initInflater(ViewGroup parent) {
        if (mLayoutInflater == null) {
            long t = System.currentTimeMillis();
            mLayoutInflater = LayoutInflater.from(parent.getContext());
        }
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.itemView.setTag(position);
        File file = mFiles[position];
        holder.icon.setImageResource(file.isDirectory() ? R.drawable.format_folder : R.drawable.format_text);
        holder.more.setVisibility(file.isDirectory() ? View.VISIBLE : View.GONE);
        holder.title.setText(file.getName());
        holder.date.setText(StringUtil.formatFileInfo(file));


    }

    @Override
    public int getItemCount() {
        return mFiles == null ? 0 : mFiles.length;
    }

    @Override
    public void onClick(View v) {
        int position = (int) v.getTag();
        File file = mFiles[position];
        if (listener != null && file.isDirectory()) {
            listener.onDirectoryClick(mFiles[position]);
        } else if (file.isFile()) {
            if (file.getName().endsWith(".xml") && file.getParent() != null && file.getParent().endsWith("shared_prefs")) {
                XMLActivity.startActivity(v.getContext(), file.getAbsolutePath());
            }
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView icon;
        ImageView more;
        TextView title;
        TextView date;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            more = itemView.findViewById(R.id.more);
            title = itemView.findViewById(R.id.title);
            date = itemView.findViewById(R.id.date);
        }
    }

    public interface OnDirClickListener {
        void onDirClick(File dir);
    }
}
